package com.example.blog.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.example.blog.dao.UserDAO;
import com.example.blog.pojo.User;

@WebServlet("/loginchk")
public class LoginCheckServlet extends HttpServlet 
{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		// 1. 获取用户提交的参数
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		
		HttpSession session = req.getSession();
		
				
		// 2. 调用DAO查询
		UserDAO dao = new UserDAO();
		User u = null;
		try {
			u = dao.findBy(username,password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		System.out.println("user="+u);
		
		if(u!=null)
		{
			// 2.1 登录成功
			// 保存登录信息到Session中
			System.out.println("登录成功,设置Session!");
			session.setAttribute("user", u);
			// 跳转首页
			resp.sendRedirect("index.jsp");
			
		}
		else
		{// 2.2登录失败，跳转到登录页重新登录
			resp.sendRedirect("login.html");
		}
			
		
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
	}

}